package com.yuwei.order

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.EnvUtils
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yuwei.base.RoutePath
import com.yuwei.common.event.BusEvent
import com.yuwei.common.event.LiveDataBus
import com.yuwei.common.mvi.BaseMviActivity
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.AddressEntity
import com.yuwei.database.entity.GoodsEntityItem
import com.yuwei.database.entity.OrderEntity
import com.yuwei.order.adapter.OrderGoodsAdapter
import com.yuwei.order.databinding.ActivityConfirmOrderBinding
import com.yuwei.order.pay.PayResult
import com.yuwei.order.pay.util.OrderInfoUtil2_0

/**
 * 提交订单页面
 */
@Route(path = RoutePath.MODULE_ORDER_CONFIRM_ORDER_ACTIVITY)
class ConfirmOrderActivity : BaseMviActivity<ActivityConfirmOrderBinding,OrderViewModel>() {
    var address : AddressEntity? = null
    private val goodsAdapter = OrderGoodsAdapter()
    private val orderList = mutableListOf<OrderEntity>()
    val APPID = "2021000118655415"
    val RSA2_PRIVATE =
        "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCpf4lEigXwChQW6OPYC4lhgBNOI25JVMgnr0DWHHfSha3SqskPDCGs/Qk8f4WVjregCgbiD6sAX4UBi50srJULiDytlKjyKVhmEe4ZTw3xG/cJ/lfQZ2/aC46tD5eFEXDh/7shGiQEflDZBXJ4amaicBCNTcISz6fxaRWtab5DbWqMvZBX2xOr0gUzu6l1RE//tXMtyJD3yyVM6/A5zIeReqSfzrok1ZAW1GhRLsvZJPpvY+v95UE2fXUt8y3piFxvheRGQ7I5RVNW4/8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wreKDjAfuWVUrIBAFfJFJKxua2u4faZtvi9aEfffIdrMY+ModvRWBl1hAoGBAN2aTPLeKIhyKNg/8IIYcST7ixgCHLnT2fxmK7qnKd4Y0QtqMyQM+xwA5A89xUU8b8Q/+Z11UkM5ysh74dFR6R7Oha9Lw8V2ovx6vQLOATEK28X7FIBsolBPwMjAn572QN9eAP+uRe5Yu2KfiX6ez8D61rEFee+3AtnRHumDJokr"
    val RSA_PRIVATE = ""

    private val SDK_PAY_FLAG = 1

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(this@ConfirmOrderActivity, "支付成功", Toast.LENGTH_SHORT).show()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(this@ConfirmOrderActivity, "支付成功", Toast.LENGTH_SHORT).show()
                        finish()
                        ARouter.getInstance().build(RoutePath.MODULE_ORDER_PAY_SUCCESS_ACTIVITY)
                            .withSerializable("addressItem", address)
                            .navigation()
                    }
                }
                else -> {}
            }
        }
    }

    fun pay() {
        if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE)) { return }
        val rsa2 = RSA2_PRIVATE.length > 0
        val params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2)
        val orderParam = OrderInfoUtil2_0.buildOrderParam(params)
        val privateKey = if (rsa2) RSA2_PRIVATE else RSA_PRIVATE
        val sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2)
        val orderInfo = "$orderParam&$sign"
        val payRunnable = Runnable {
            val alipay = PayTask(this@ConfirmOrderActivity)
            val result: Map<String, String> = alipay.payV2(orderInfo, true)
            Log.i("msp", result.toString())
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    override fun successData(it: UiState.onSuccess<*>) {
        when(it.type){
            "insertOrder"->{
            }
            "updateOrder"->{
            }
            "getByStatus"->{
                orderList.clear()
                orderList.addAll(it.data as List<OrderEntity>)
                orderList.forEach {
                    it.order_status = 1
                    vm.sendIntent(OrderIntent.updateOrder(it))
                }
                goodsAdapter.data.addAll(orderList)
                goodsAdapter.notifyDataSetChanged()
                totalMoney()
            }
        }
    }

    override fun failureData(error: String) {

    }

    override fun initView() {
        binding.addOrderBack.setOnClickListener {
            finish()
        }
        binding.goodsRv.adapter = goodsAdapter
        binding.goodsRv.layoutManager = LinearLayoutManager(this)
        goodsAdapter.addChildClickViewIds(R.id.goods_add,R.id.goods_subtract)
        //列表操作
        goodsAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.goods_add -> {
                    goodsAdapter.data[position].count++
                    goodsAdapter.notifyItemChanged(position)
                    totalMoney()
                }
                R.id.goods_subtract -> {
                    if (goodsAdapter.data[position].count > 1){
                        goodsAdapter.data[position].count--
                        totalMoney()
                        goodsAdapter.notifyItemChanged(position)
                    }else{
                        ToastUtils.showShort("商品数量不能小于1")
                    }
                }
            }
        }
        //跳转地址页面
        binding.selectAddress.setOnClickListener {
            ARouter.getInstance().build(RoutePath.MODULE_ORDER_ADDRESS_ACTIVITY).navigation()
        }
    }

    override fun initData() {
        vm.sendIntent(OrderIntent.getByStatus(0))
        //提交订单
        binding.orderPay.setOnClickListener {
            if(address!=null){
                orderList.forEach {
                    it.order_status = 2
                    vm.sendIntent(OrderIntent.updateOrder(it))
                }
                //开启沙箱
                EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                pay()
            }else{
                ToastUtils.showShort("请选择收货地址")
            }

        }
        //修改地址
        binding.ivEdit.setOnClickListener {
            ARouter.getInstance().build(RoutePath.MODULE_ORDER_ADDRESS_ACTIVITY).navigation()
        }
    }
    //计算金钱
    fun totalMoney(){
        var totalMoney = 0
        goodsAdapter.data.forEach {
            totalMoney += it.goods_default_price * it.count
        }
        binding.totalMoney.text = "${totalMoney}.00"
    }

    override fun onResume() {
        super.onResume()
        LiveDataBus.getDefault<BusEvent>("address").observe(this@ConfirmOrderActivity){
            address = it.data as AddressEntity
        }
        if(address!=null){
            binding.selectAddress.visibility = View.GONE
            binding.addressInfo.visibility = View.VISIBLE
            binding.tvAddress.text = address?.address + address?.fullAddress
            binding.tvName.text = address?.name
            binding.tvPhone.text = address?.phone
            binding.tvAddressLabel.text = address?.tag

        }else{
            binding.selectAddress.visibility = View.VISIBLE
            binding.addressInfo.visibility = View.GONE
        }
    }
}